# coding= utf-8

import sys
import codecs
import warnings
import pymongo
import time

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
warnings.filterwarnings("ignore")


class Low:
    def __init__(self):
        self.country_desc = ''
        self.month = sys.argv[1]
        # self.month = '2024-08'

        # 连接MongoDB
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        mydb = self.myclient["xp_analyse"]
        self.my_product = mydb["wt_order_product"]
        self.low_product = mydb["wt_product"]
        self.low_order = mydb["wt_low_order"]
        self.task = mydb["wt_task"]

    # 更新订单里的asin订单量
    def update_low_order_num(self):
        # 更新状态为处理中
        self.task.update_one({"month": self.month}, {"$set": {"low_orders_completed.update_low.loading": True}})

        pipeline = [
            {'$match': {'month': self.month}},
            {
                '$group': {
                    '_id': {
                        'asin': '$asin',
                        'month': '$month',
                        'group_name': '$group_name',
                        'locale': '$locale'
                    },
                    'asin': {'$first': '$asin'},
                    'locale': {'$first': '$locale'},
                    'group_name': {'$first': '$group_name'},
                    'title': {'$first': '$title'},
                    'image': {'$first': '$image'},
                    'buy_box_current': {'$first': '$buy_box_current'},
                    'sales_rank_current': {'$first': '$sales_rank_current'},
                    'reviews_rating': {'$first': '$reviews_rating'},
                    'reviews_review_count': {'$first': '$reviews_review_count'},
                    'status': {'$first': '$status'},
                    'categories_tree': {'$first': '$categories_tree'},
                    'order_num': {
                        '$sum': '$order_num'
                    },
                },
            }
        ]

        for item in self.my_product.aggregate(pipeline, allowDiskUse=True):
            # 法德意西为欧洲，英国、美国、日本、加拿大
            country_desc = ''
            country = item.get('locale')
            if country in ['fr', 'de', 'it', 'es']:
                country_desc = '欧洲四国'
            elif country == 'uk':
                country_desc = '英国'
            elif country == 'us':
                country_desc = '美国'
            elif country == 'jp':
                country_desc = '日本'
            elif country == 'ca':
                country_desc = '加拿大'

            low_product_info = self.low_product.find_one(
                {'month': self.month, 'country': country, 'asin': item.get('asin'),
                 'group_name': item.get('group_name')})
            if low_product_info:
                print('已存在，更新' + str(low_product_info.get('order_num')) + '为' + str(item.get('order_num')))
                self.low_product.update({'month': self.month, 'country': country, 'asin': item.get('asin'),
                                         'group_name': item.get('group_name')},
                                        {"$set": {"order_num": item.get('order_num')}})
            else:
                print('插入新记录，asin：' + item.get('asin', ''))
                value = dict([
                    ['domain_id', translate_locale(country)],
                    ['country', country],
                    ['country_desc', country_desc],
                    ['month', self.month],
                    ['asin', item.get('asin', '')],
                    ['group_name', item.get('group_name')],
                    ['image', item.get('image')],
                    ['title', item.get('title', '')],
                    ['buy_box_current', item.get('buy_box_current')],
                    ['sales_rank_current', item.get('sales_rank_current')],
                    ['reviews_rating', item.get('reviews_rating')],
                    ['reviews_review_count', item.get('reviews_review_count')],
                    ['categories_tree', item.get('categories_tree')],
                    ['status', '在售'],
                    ['order_num', item.get('order_num')],
                    ['create_time', int(time.time())],
                    ['update_time', int(time.time())],
                ])
                self.low_product.insert(value)

        print('补充完毕，开始整合数据')
        self.comb_data_to_low()

    # 整合数据
    def comb_data_to_low(self):
        low_insert = []

        # 创建索引
        indexlist = self.low_order.index_information()
        if not indexlist:
            self.low_order.create_index("asin")
            self.low_order.create_index("country_desc")
            self.low_order.create_index("group_name")
            self.low_order.create_index("month")
            self.low_order.create_index("status")

        pipeline = [
            {'$match': {'month': self.month}},
            {
                '$group': {
                    '_id': {
                        'asin': '$asin',
                        'month': '$month',
                        'group_name': '$group_name',
                        'country_desc': '$country_desc'
                    },
                    'title': {'$first': '$title'},
                    'image': {'$first': '$image'},
                    'categories_tree': {'$first': '$categories_tree'},
                    'order_num': {
                        '$sum': '$order_num'
                    },
                    'statuses': {'$addToSet': '$status'},
                    'unique_title': {'$addToSet': '$title'},
                },
            },
            {
                '$project': {
                    '_id': 1,
                    'order_num': 1,
                    'title': 1,
                    'image': 1,
                    'categories_tree': 1,
                    'unique_title': 1,
                    'status': {
                        '$cond': [
                            {'$in': ['不在售', '$statuses']},
                            '不在售',
                            '在售'
                        ]
                    }
                }
            }
        ]
        for item in self.low_product.aggregate(pipeline, allowDiskUse=True):
            order_num = item.get('order_num')
            if order_num <= 10:
                # 自动标记不在售和店铺无
                limit_type = ''
                limit_reason = ''

                status = item.get('status')
                if status == '不在售':
                    limit_type = 0
                    limit_reason = '系统标记不在售'

                unique_title = item.get('unique_title', [None])
                if all_none(unique_title) and order_num == 0:
                    limit_type = 1
                    limit_reason = '系统标记店铺无'

                # 有订单的数据，标记在售
                if order_num > 0:
                    status = '在售'

                value = dict([
                    ['asin', item['_id']['asin']],
                    ['month', item['_id']['month']],
                    ['group_name', item['_id']['group_name']],
                    ['country_desc', item['_id']['country_desc']],
                    ['title', item.get('title', '')],
                    ['image', item.get('image', '')],
                    ['categories_tree', item.get('categories_tree', '')],
                    ['order_num', item.get('order_num', '')],
                    ['status', status],
                    ['limit_type', limit_type],
                    ['limit_reason', limit_reason],
                    ['is_human', 0],
                    ['create_time', int(time.time())],
                    ['update_time', int(time.time())],
                ])
                low_insert.append(value)

        # 插入低订单产品表
        if len(low_insert) > 0:
            result = self.low_order.insert_many(low_insert)

            # 检查插入操作是否成功
            if result.acknowledged:
                print('插入低订单表成功，共计' + str(len(low_insert)) + '条！')
            else:
                print('插入低订单失败！')
        else:
            print('暂无低订单数据！')

        # 更新状态为已完成
        self.task.update_one({"month": self.month}, {"$set": {"low_orders_completed.update_low.value": 1, "low_orders_completed.update_low.loading": False}})
        print('补全asin已完成！')


def translate_locale(domain):
    dis = {'us': 1, 'uk': 2, 'de': 3, 'fr': 4, 'jp': 5, 'ca': 6, 'it': 8, 'es': 9, 'in': 10, 'mx': 11}
    return dis.get(domain)


def all_none(lst):
    return all(element is None for element in lst)


low = Low()
# low.comb_data_to_low()
low.update_low_order_num()
